﻿

using adb;
using Masuit.Tools.Systems;
using Microsoft.Extensions.Configuration;
using System;
using System.Diagnostics;
using System.IO;
using utils;
using static System.Net.Mime.MediaTypeNames;

namespace VideoCheck.AppCode
{
    /// <summary>
    /// 视频截图
    /// </summary>
    public class VideoCutImage
    {
        /// <summary>
        /// 从网络中获取视频的第一贞图片
        /// </summary>
        /// <param name="patch">路径</param>
        /// <returns></returns>
        /// 
        //private static StreamWriter writer = new StreamWriter("logs/path_to_log_file.log", true);
        //private static IConfigurationRoot configurations;
        // private static tPowerStationDevice deviceItem;


        // linux下
        public static byte[] GetImageOfVideo(string patch, string tmpPath)
        {
            string path1 = Path.Combine(tmpPath, "image");
            DirectoryInfo directoryInfo = new DirectoryInfo(path1);
            if (!((FileSystemInfo)directoryInfo).Exists)
                directoryInfo.Create();
            SnowFlake instance = SnowFlake.GetInstance();
            string str = Path.Combine(path1, instance.GetUniqueId() + ".jpg");
            if (!VideoCutImage.RunCmd2("CutImag.sh", " \"" + patch + "\" " + str))
                return (byte[])null;
            FileInfo fileInfo = new FileInfo(str);
            if (!((FileSystemInfo)fileInfo).Exists)
                return (byte[])null;
            FileStream fileStream = fileInfo.OpenRead();
            byte[] imageOfVideo = new byte[fileInfo.Length];
            if (((Stream)fileStream).CanRead)
                ((Stream)fileStream).Read(imageOfVideo, 0, imageOfVideo.Length);
            ((Stream)fileStream).Dispose();
            ((FileSystemInfo)fileInfo).Delete();
            return imageOfVideo;
        }
        // private static string shuangyinhao = "\"";
        // // windows下
        // public static byte[] GetImageOfVideo(string patch, string tmpPath)
        // {
        //     string savePath = Path.Combine(tmpPath, "image");
        //     DirectoryInfo dinfo = new DirectoryInfo(savePath);
        //     if (dinfo.Exists == false)
        //     {
        //         dinfo.Create();
        //     }
        //     var sf = SnowFlake.GetInstance();
        //     savePath = Path.Combine(savePath, $"{sf.GetUniqueId()}.jpg");
        //     string exe = "D:/ffmpeg/bin/ffmpeg.exe";
        //     string cmd = $" -i {shuangyinhao}{patch}{shuangyinhao} -vf fps=1/1 -s 640*400 {shuangyinhao}{savePath}{shuangyinhao} -hide_banner";
        //     if (RunCmd2(exe, cmd))
        //     {
        //         FileInfo info = new FileInfo(savePath);
        //         if (info.Exists)
        //         {
        //             var stream = info.OpenRead();
        //             byte[] imgBytes = new byte[info.Length];
        //             if (stream.CanRead)
        //             {
        //                 stream.Read(imgBytes, 0, imgBytes.Length);
        //             }
        //             stream.Dispose();
        //             info.Delete();
        //             return imgBytes;
        //         }
        //         else
        //         {
        //             return null;
        //         }
        //     }
        //     return null;
        // }

        /// <summary>
        /// 运行cmd命令
        /// 不显示命令窗口
        /// </summary>
        /// <param name="cmdExe">指定应用程序的完整路径</param>
        /// <param name="cmdStr">执行命令行参数</param>
        static bool RunCmd2(string cmdExe, string cmdStr)
        {
            bool result = false;
            try
            {
                using (Process p = new Process())
                {
                    p.StartInfo.FileName = cmdExe;//要调用外部程序的绝对路径
                    string strArg = cmdStr;
                    
                    p.StartInfo.Arguments = strArg;
                   
                    p.StartInfo.UseShellExecute = false;//不使用操作系统外壳程序启动线程(一定为FALSE,详细的请看MSDN)
                    p.StartInfo.RedirectStandardError = true;//把外部程序错误输出写到StandardError流中(这个一定要注意,FFMPEG的所有输出信息,都为错误输出流,用StandardOutput是捕获不到任何消息的...这是我耗费了2个多月得出来的经验...mencoder就是用standardOutput来捕获的)
                    p.StartInfo.CreateNoWindow = true;//不创建进程窗口
                    p.ErrorDataReceived += new DataReceivedEventHandler(Output);//外部程序(这里是FFMPEG)输出流时候产生的事件,这里是把流的处理过程转移到下面的方法中,详细请查阅MSDN
                    p.Start();//启动线程
                    p.BeginErrorReadLine();//开始异步读取
                    p.WaitForExit();//阻塞等待进程结束
                    p.Close();//关闭进程
                    result = true;
                }
            }
            catch (Exception e)
            {
                writeExceptionLogUtil.writeLogException(e,"/root/logs","VideoCheck");
                Console.WriteLine(e.Message);
            }
            return result;
        }
       
        private static async void Output(object sendProcess, DataReceivedEventArgs output)
        {
            if (!String.IsNullOrEmpty(output.Data))
            {
                //处理方法...
                //Console.WriteLine(output.Data);
     
            }
        }
    }
}
